package sk.tuke.kephera.connector;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public final class KepheraUtils {
    private static ObjectMapper mapper = new ObjectMapper();

    private KepheraUtils() {
        // lib pattern
    }

    /**
     * Opravy ze na konci je mezera mezi zavorkami, protoze to ma patrik na TVRDO kontrolovane ve zdorjaku, az to
     * odstrani neni potreba
     * 
     * @param txtData
     * @return
     */
    private static String fixEndOfJson(String txtData) {
        String f = txtData.substring(0, txtData.lastIndexOf("}}"));
        return f.concat("} }");
    }

    /**
     * Prevede objekt zpravy na text
     * @param protokol
     * @return
     */
    public static String toJson(KepheraMsg protokol) {
        try {
            return fixEndOfJson(mapper.writeValueAsString(protokol));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Prevede txt zpravu na objekt protokolu
     * @param txt
     * @return
     */
    public static KepheraMsg fromJson(String txt) {
        try {
            return mapper.readValue(txt, KepheraMsg.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
